const request = require('../utils/request')
const md5 = require('md5')
const jwt = require('jsonwebtoken')
const { secretKey } = require('../utils/secret')
const { successStatus, errorStatus } = require('../utils/status')
// 登录
async function userLogin (req, res) {
  const {username, password} = req.body
  const pwd = md5(password)
  const result = await request(`select * from user where username='${username}' and password='${pwd}'`)
  if (result.length) {
    const tokenData = jwt.sign({id: result[0].id}, secretKey, {expiresIn: '2h'})
    successStatus.RESULT.data = {
      msg: '登录成功',
      token: 'Bearer ' + tokenData
    }
    if (tokenData) {
      res.status(200).json(successStatus.RESULT)
      await request(`update user set token='${tokenData}' where id=${result[0].id}`)
    }
  } else {
    errorStatus.RESULT.msg = "登录失败，用户名或密码错误"
    res.status(400).json(errorStatus.RESULT)
  }
}
// 注册
async function userRegister (req, res, next) {
  const {username, password} = req.body
  const result = await request(`select * from user where username='${username}'`)
  if (result.length > 0) {
    errorStatus.RESULT.msg = "用户名已注册，请重新注册"
    res.status(400).json(errorStatus.RESULT)
  } else {
    const pwd = md5(password)
    const result = await request(`insert into user set username='${username}',password='${pwd}'`)
    if (result.affectedRows > 0) {
      successStatus.RESULT.data = {
        msg: '用户名注册成功'
      }
      res.status(200).json(successStatus.RESULT)
      next()
    } else {
      errorStatus.RESULT.msg = "注册失败，用户名或密码错误"
      res.status(400).json(errorStatus.RESULT)
    }
  }
}

module.exports = {
  userLogin,
  userRegister
}